﻿#include "formrecordcontrol.h"
#include "ui_formrecordcontrol.h"
#include "formtoolboxwidget.h"
#include "formtoolboxinfowidget.h"
#include "../excelthread.h"
#include "../excelengine.h"
#include "../ui/basewidget.h"
#include "../ui/formitemwidgetgroup.h"
#include "../loadingwidget.h"
#include "../client/clientthread.h"
//#include "../utils/excelhandle.h"

#include <QGraphicsDropShadowEffect>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QStandardPaths>
#include <QListWidget>
#include <QComboBox>
#include <QMessageBox>
#include <QDateEdit>
#include <QLabel>
#include <QDateTime>
#include <QDebug>
#include <QSettings>
#include <QThreadPool>

#include <QFileDialog>

#include <QTimer>
#include <QVBoxLayout>
#include <QCheckBox>
#include <QToolBar>
#include <QMenu>
#include <QFileInfo>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlTableModel>

#include <QMapIterator>

FormRecordControl::FormRecordControl(RecordControlType type, QWidget *parent) :
    BaseWidget(parent),widget_load(nullptr),m_Puttimer(nullptr),m_cycle(-1),m_countStartPut(-1),/*widget_selectItem(nullptr),*/
    m_defaultDataPath(""),m_parentWidget(NULL),widgetmsg(NULL),
    ui(new Ui::FormRecordControl)
{
    ui->setupUi(this);

    QSettings set;
    m_defaultDataPath = set.value("general/DefaultSaveDir",QStandardPaths::writableLocation(QStandardPaths::DataLocation)+ QDir::separator() + "data").toString();

//    qDebug()<<"default path:"<<m_defaultDataPath;

    ui->btn_showEnable->setVisible(false);

//    ui->tableWidget->clear();
//    for(int i = 0; i < ui->tableWidget->columnCount();i++)
//        ui->tableWidget->removeColumn(i);

    connect(ui->tableWidget,&QTableWidget::cellChanged,[=](int /*row*/, int column){
        ui->tableWidget->resizeColumnToContents(column);
    });

    ui->btn_setcountCancel->setVisible(false);
    ui->btn_setcountOK->setVisible(false);
    ui->lineedit_count->setVisible(false);
    ui->btn_setcount->setVisible(false);
    connect(ui->btn_setcount,&QToolButton::clicked,[=]{
        ui->btn_setcount->setVisible(false);
        ui->btn_setcountCancel->setVisible(true);
        ui->btn_setcountOK->setVisible(true);
        ui->lineedit_count->setVisible(true);
    });
    connect(ui->btn_setcountCancel,&QToolButton::clicked,[=]{
        ui->btn_setcount->setVisible(true);
        ui->btn_setcountCancel->setVisible(false);
        ui->btn_setcountOK->setVisible(false);
        ui->lineedit_count->setVisible(false);
    });
    connect(ui->btn_setcountOK,&QToolButton::clicked,[=]{
        if(ui->toolBox->currentWidget()){
            qobject_cast<FormToolBoxInfoWidget*>(ui->toolBox->currentWidget())->setcount(ui->lineedit_count->text().toInt());
        }
    });

    connect(ui->btn_return,&QToolButton::clicked,[=]{
        this->close();
    });

    list_preItem.clear();
    if(type != RCT_Add)
        Init();//实际操作界面
    else
        Init_Add();//用作导入界面
    m_Puttimer = new QTimer(this);
    m_Puttimer->setProperty("countStart",1);
    connect(m_Puttimer,&QTimer::timeout,[=]{
        m_Puttimer->setInterval(m_cycle);//周期
        m_Puttimer->setProperty("first",m_Puttimer->interval());
        m_Puttimer->setProperty("countStart",m_Puttimer->property("countStart").toInt()+1);

        //thread to put opreation.
        startWeighOpt();
        //End.

        //prepare for next timer of next item.
        if(m_Puttimer->property("countStart").toInt() > m_countStartPut){
            QString key = m_ItemData.getTBStartTimes().firstKey();//m_Puttimer->property("ItemIndex").toString();

            m_Puttimer->setProperty("countStart",1);
            m_cycle = 1;//1 minute;
            m_countStartPut = -1;
//            m_ItemData.removeItem(m_ItemData.getTBStartTimes().firstKey());
            //check the value is correct.
            QString tbname = "";
            for(int it = 0;it<list_preItem.count();it++){
                if(m_ItemData.getTBStartTimes().find(list_preItem.at(it)) != m_ItemData.getTBStartTimes().end()){
                    tbname = list_preItem.at(it);
//                    interval = currentTime.msecsTo(m_ItemData.getTBStartTime(tbname));
                    list_preItem.removeAt(it);
                    break;
                }
            }
            m_ItemData.setCurrentTb(tbname);

            //next item.
            if(!list_preItem.count())//全部完成
                m_Puttimer->stop();
            else {//有待完成项目
                if(!tbname.isEmpty()){
                    m_cycle = m_ItemData.getTBCycleMsecs(tbname);
                    m_countStartPut = m_ItemData.getTBCount(tbname);
                    QTime currenttime = QTime(QDateTime::currentDateTime().time().hour(),QDateTime::currentDateTime().time().minute(),QDateTime::currentDateTime().time().second());
                    int interval = currenttime.msecsTo(m_ItemData.getTBStartTime(tbname));
                    qDebug()<<"restart timer:"<<interval;
                    m_Puttimer->start(interval);//m_ItemData
                }
            }
        }
//            if(m_ItemData.getTBStartTimes().count()<1)
//                m_Puttimer->stop();
//            else if(m_ItemData.getTBStartTimes().count()>1){
//                m_cycle = m_ItemData.getFirstCycleMsecs();
//                m_countStartPut = m_ItemData.getFirstCount();
//                int interval = QDateTime::currentDateTime().time().msecsTo(m_ItemData.getFirstStartTime());
//                qDebug()<<"restart timer:"<<interval;
//                m_Puttimer->start(interval);//m_ItemData
//            }
//        }
    });
}

FormRecordControl::~FormRecordControl()
{
//    if(widget_selectItem){
//        delete widget_selectItem;
//        widget_selectItem = NULL;
//    }
    //if(widget_load){
    //    delete widget_load;
    //    widget_load = NULL;
    //}
    if(m_Puttimer){
        m_Puttimer->stop();
        delete m_Puttimer;
        m_Puttimer = nullptr;
    }
    delete ui;
}

bool FormRecordControl::loadDataFromSql(QString groupnum)
{
    if(groupnum.isEmpty())
        return false;

    QStringList listtbl = getTablesName(groupnum);
    QListIterator<QString> itor(listtbl);
    itor.toBack();
    int _total = listtbl.count()-1;
    while(itor.hasPrevious()){
        QString tbname(itor.previous());
        FormToolBoxInfoWidget *it_widget  = nullptr ;
//        if(qobject_cast<FormToolBoxInfoWidget*>(ui->toolBox->widget( _total)) && isexist)
//            it_widget = (FormToolBoxInfoWidget*)ui->toolBox->widget( _total);
//        else
        it_widget = new FormToolBoxInfoWidget(ui->toolBox);
        QTime timeStart = QTime(m_ItemData.getStartTime().hour() + _total,//every item add one hour
                                m_ItemData.getStartTime().minute(),
                                m_ItemData.getStartTime().second());
        QTime cycleTime;
        int _count = 1;

        QSettings setting;
        setting.beginGroup("GroupData");
        timeStart = setting.value(QString("%1/%2").arg(groupnum,QString("%1_starttime").arg(tbname)),timeStart).toTime();//,m_ItemData.getFirstStartTime());
        cycleTime = setting.value(QString("%1/%2").arg(groupnum,QString("%1_cyletime").arg(tbname)),m_ItemData.getCycleTime()).toTime();//,m_ItemData.getFirstCycleTime());
        _count = setting.value(QString("%1/%2").arg(groupnum,QString("%1_count").arg(tbname)),m_ItemData.getCount()).toInt();//,m_ItemData.getFirstCount());

        it_widget->setcount(_count);
        it_widget->setStartTime(timeStart);
        it_widget->setCyleTime(cycleTime);

//        initTableWidget(tbname);
        m_ItemData.insertTBCount(tbname,it_widget->getcount());
        m_ItemData.insertTBCycleTime(tbname,it_widget->getCyleTime());
        m_ItemData.insertTBStartTime(tbname,it_widget->getStartTime());

        ui->toolBox->insertItem(0,it_widget,tbname);

        connect(it_widget,&FormToolBoxInfoWidget::sig_StartTimeChangeed,[=](const QTime &time){
            m_ItemData.insertTBStartTime(tbname,time);
            QSettings setting;
            setting.beginGroup("GroupData");
            setting.setValue(QString("%1/%2").arg(groupnum,QString("%1_starttime").arg(tbname)),
                             m_ItemData.getTBStartTime(tbname));
        });
        connect(it_widget,&FormToolBoxInfoWidget::sig_CycleTimeChangeed,[=](const QTime &time){
            m_ItemData.insertTBCycleTime(tbname,time);
            QSettings setting;
            setting.beginGroup("GroupData");
            setting.setValue(QString("%1/%2").arg(groupnum,QString("%1_cyletime").arg(tbname)),
                             m_ItemData.getTBCycleTime(tbname));
        });
        connect(it_widget,&FormToolBoxInfoWidget::sig_CountStartPutChangeed,[=](const QString &count){
            m_ItemData.insertTBCount(tbname,count.toInt());
            QSettings setting;
            setting.beginGroup("GroupData");
            setting.setValue(QString("%1/%2").arg(groupnum,QString("%1_count").arg(tbname)),
                             m_ItemData.getTBCount(tbname));
        });

        _total--;
    }

    connect(ui->btn_showEnable,&QToolButton::clicked,[=]{
        QWidget *widget = createSelectTBar(listtbl);
        widget->show();
        widget->move(QCursor::pos() + QPoint(0,-widget->height()));
    });

    connect(ui->toolBox,&QToolBox::currentChanged,[=](int index){
        getCurrentItemData(ui->toolBox->itemText(index),true);
    });

    if(ui->toolBox->count()){
        ui->toolBox->setCurrentIndex(0);
        //set ui:the current item.(direct by start time with current time.)
        foreach(QTime time,m_ItemData.getTBStartTimes()){
            qint32 ms = QDateTime::currentDateTime().time().msecsTo(time);
            if(ms < 0){
                continue;
            }else{
                for(int i = 0;i<ui->toolBox->count();i++) {
                    QString key = m_ItemData.getTBStartTimes().key(time);
                    if(ui->toolBox->itemText(i) == key){
                        ui->toolBox->setCurrentIndex(i);
                        break;
                    }
                }
                break;
            }
        }
        return true;
    }else
        return false;
}

bool FormRecordControl::loadDataFromSql(GroupItemData data)
{
//    m_ItemData = data;
    setGroupData(data);
    return loadDataFromSql(m_ItemData.getGroupNum());
}

QString FormRecordControl::ImportData(int groupNum , int itemIndex, QString custfile)
{
    QString matchFileName(custfile.isEmpty()?getItemExlFileName(groupNum):custfile);
    if(matchFileName.isEmpty())
    {
        QFile fileExl(matchFileName);
        if(!fileExl.exists()){
            QMessageBox::about(this,QStringLiteral(""),QStringLiteral("数据文件夹未发现数据文件，请先准备数据文件,当前数据文件夹路径为：") + (m_defaultDataPath)
                               +QStringLiteral("\n对应分组为:")+QString::number(itemIndex+1));
            return "File not Exists!";
        }
    }

    if(itemIndex != -1){
        //disable the widget
        if(ui->toolBox->widget(itemIndex))
            ui->toolBox->widget(itemIndex)->setEnabled(false);

        map_loadingChk.insert(groupNum,QString::number(groupNum));
        ExcelThread *threadexlsR = new ExcelThread(matchFileName,ExcelThread::ExcelOperatorType::ReadData,this);
        threadexlsR->setGroup(groupNum);
        threadexlsR->setItemIndex(itemIndex);
        threadexlsR->start();
        connect(threadexlsR,&ExcelThread::sig_finishedWithExlRecord,this,&FormRecordControl::updateToolBoxWithRecord,Qt::QueuedConnection);
    }
    return "";//success.
}

void FormRecordControl::setGroupData(GroupItemData data)
{
    m_ItemData = data;
    if(m_ItemData.getEXLFileName().isEmpty())
        m_ItemData.setEXLFileName(getItemExlFileName(m_groupNum.toInt()));
    if(m_ItemData.getDBFileName().isEmpty())
        m_ItemData.setDBFileName(getItemDBFileName(m_groupNum.toInt()));
//    qDebug()<<"setGroupData:"<<m_ItemData.getEXLFileName()<<getItemDBFileName(m_groupNum.toInt())<<m_groupNum;
}

void FormRecordControl::putWeigh(QString group)
{
    //check if ignor error.
    //1.connect to server first to get puWeigh value.
    //2.connect again to start weigh.
    qDebug()<<"putWeight start"<<m_ItemData.getCount()<<m_ItemData.getCycleTime()<<m_ItemData.getGroupNum()<<m_ItemData.getDBFileName()
           <<m_ItemData.getIpadd()<<m_ItemData.getStartTime();
}

void FormRecordControl::putWeigh(GroupItemData groupdata)
{
    QTime currentTime = QTime(QDateTime::currentDateTime().time().hour(),QDateTime::currentDateTime().time().minute(),QDateTime::currentDateTime().time().minute());

    int interval = -1;

    QList<QTime> timelist;
    foreach(QTime timeit,m_ItemData.getTBStartTimes()){
        timelist.append(timeit);
    }
    qSort(timelist.begin(),timelist.end());//sort the time.
    for(int i = 0;i<timelist.count();i++){
        QTime time = timelist.at(i);
        if(currentTime.msecsTo(time) >0){
            list_preItem.append(/*.push_back(*/m_ItemData.getTBStartTimes().key(time));
        }
    }
//    foreach(QTime time,m_ItemData.getTBStartTimes()){

////        if(QDateTime::currentDateTime().time().msecsTo(time) == 0){
////            qDebug()<<"check time_______ :"<<QDateTime::currentDateTime().time()<<time;
////            interval = -1 ;//it wont be start.
////        }
////        else
//            if(!QDateTime::currentDateTime().time().msecsTo(time)){
////            m_ItemData.getTBStartTimes().remove(m_ItemData.getTBStartTimes().key(time));
////            m_ItemData.getTBCycleTimes().remove(m_ItemData.getTBStartTimes().key(time));
////            m_ItemData.getTBCounts().remove(m_ItemData.getTBStartTimes().key(time));
//        }
//    }

    //check the value is correct.
    for(int it = 0;it<list_preItem.count();it++){
        if(m_ItemData.getTBStartTimes().find(list_preItem.at(it)) != m_ItemData.getTBStartTimes().end()){
            interval = currentTime.msecsTo(m_ItemData.getTBStartTime(list_preItem.at(it)));
            m_ItemData.setCurrentTb(list_preItem.at(it));
            list_preItem.removeAt(it);
            break;
        }
    }

    if(interval){
        //cycle time for global.
        m_cycle = m_ItemData.getTBCycleMsecs(m_ItemData.currentTable());
        //count for global.
        m_countStartPut = m_ItemData.getTBCount(m_ItemData.currentTable());

        if(m_Puttimer){
            m_Puttimer->start(interval);//go to timer connect slot to handle it (thread)
            m_Puttimer->setProperty("first",m_Puttimer->interval());
        }
    }else{
        QMessageBox::about(this,QStringLiteral(""),QStringLiteral("please set start time. or check the data wheather had imported."));
        return;
    }
}

void FormRecordControl::startWeighOpt()
{
    ClientThread *clientThread = new ClientThread(m_ItemData.currentTable()/*m_ItemData*/);// (groupid,itor_ip.value());
    clientThread->setData(m_ItemData);
    {
        //save data to reg.
        QSettings setting ;
        setting.beginGroup("GroupData");
        setting.setValue(QString("%1/%2").arg(m_ItemData.getGroupNum(),QString("%1_starttime").arg(m_ItemData.currentTable())),m_ItemData.getFirstStartTime());
        setting.setValue(QString("%1/%2").arg(m_ItemData.getGroupNum(),QString("%1_cyletime").arg(m_ItemData.currentTable())),m_ItemData.getFirstCycleTime());
        setting.setValue(QString("%1/%2").arg(m_ItemData.getGroupNum(),QString("%1_count").arg(m_ItemData.currentTable())),m_ItemData.getFirstCount());
    }

    //更新socket返回各种状态-m_parentWidget(父控件)
    connect(clientThread,&ClientThread::sig_UpdateState,[=](GroupItemData _data,BatchFeed::ClientConnectType type,QString errorstr){
        QString str_status = "";
        switch(type){
        case BatchFeed::ClientConType_WeighConnected:
            str_status = QStringLiteral("连接成功");
            break;
        case BatchFeed::ClientConType_StartedWeigh:
            str_status = QStringLiteral("开始称料");
            break;
        case BatchFeed::ClientConType_FinishedWeigh:
            str_status = QStringLiteral("称料中...");
            break;
        case BatchFeed::ClientConType_ReadyReadWeighValue:
            str_status = QStringLiteral("实际称量值返回");
            break;
        case BatchFeed::ClientConType_PutConnected:
            str_status = QStringLiteral("准备投放...");
            break;
        case BatchFeed::ClientConType_StartPut:
            str_status = QStringLiteral("开始投放");
            break;
        case BatchFeed::ClientConType_FinishedPut:
            str_status = QStringLiteral("投放完成");
            break;

        case BatchFeed::ClientConType_WeighError:
            str_status = QStringLiteral("称量时出错");
            break;
        case BatchFeed::ClientConType_PutError:
            str_status = QStringLiteral("投放时出错");
            break;
        }
        if(m_parentWidget)
            m_parentWidget->updateStatus(str_status);
        if(!errorstr.isEmpty())
            emit sig_showMsg(QString("%1 %2:\n%3\t(%4)").arg(QStringLiteral("第")+_data.getGroupNum()+QStringLiteral("组"),
                                                       _data.currentTable(),
                                                       str_status,
                                                       QStringLiteral("出错原因:")+errorstr));
    });

    //! 1
    connect(clientThread,&ClientThread::sig_finishedPutWeigh,[=](QString tbname,QMap<QString,QString> m_mapPutvalue){
        //投料成功/后返回对应实际称量值
        QHash<QString,QString> h_value;

        QMapIterator<QString,QString> itor(m_mapPutvalue);
        while (itor.hasNext()){
            itor.next();
            h_value.insert(itor.key(),itor.value());
        }
        m_eachRealValue.insert(tbname,h_value);

//        QTableWidget *tablwnd = m_ItemData.getTableWidget(tbname);
//        QTableWidget *tablwnd = ui->tableWidget;

        if(ui->tableWidget->rowCount()!=3)
            ui->tableWidget->setRowCount(3);
        for(int i = 0;i<ui->tableWidget->columnCount();i++){
            QTableWidgetItem *item_boxnum = ui->tableWidget->item(0,i);
            QString boxnum = item_boxnum->text();
            QHash<QString,QString>::const_iterator itor_insert = h_value.constFind(boxnum);
            if(itor_insert != h_value.constEnd()){
                QTableWidgetItem *item = new QTableWidgetItem;
                QString inputStr = itor_insert.value();
                if(inputStr == "0"){
                    inputStr = "Off";//离线
                    item->setBackgroundColor(QColor(Qt::red));
                    item->setForeground(QBrush(QColor(Qt::white)));
                }
                item->setText(inputStr);
                ui->tableWidget->setItem(2,i,item);
            }
        }

        qDebug()<<"Finished put in.get sig_finishedPutWeigh.";
        //! [1] update state of widget.
        //Todo.
        //! [1] End.
    });
    clientThread->start();
}

void FormRecordControl::updateEnable(int groupnum, int index)
{
    QRegExp regnum("[\\d]{1,}");
    if(regnum.indexIn(ui->toolBox->itemText(ui->toolBox->currentIndex())) != -1){
        if(regnum.cap(0).toInt() == groupnum){
            auto *it_widget = qobject_cast<FormToolBoxWidget*>(ui->toolBox->currentWidget());
            it_widget->setCurrentItem();
        }
    }

    if(ui->toolBox->widget(index))
        if(!ui->toolBox->widget(index)->isEnabled())
            ui->toolBox->widget(index)->setEnabled(true);
    map_loadingChk.remove(groupnum);
    if(!map_loadingChk.count()){
        if(widget_load){
            widget_load->stop();
        }
    }
}

void FormRecordControl::updateToolBoxWithRecord(excelHandle rec)
{
    QRegExp regnum("[\\d]{1,}");
    if(regnum.indexIn(ui->toolBox->itemText(ui->toolBox->currentIndex())) != -1){
        //load current Item Data.
        if(regnum.cap(0).toInt() == rec.getGroupNum().toInt()){
            //addItem to toolbox.
            auto *it_widget = qobject_cast<FormToolBoxWidget*>(ui->toolBox->currentWidget());
            it_widget->clear();
            foreach(QString str,rec.getTables())
                it_widget->addItem(str);
        }
    }

    QString sqlfilePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QDir::separator() + "config";
    QString sqlfileName = sqlfilePath + QDir::separator() + QString("dbrec_%1.db").arg(rec.getGroupNum());
    QDir dir_sql(sqlfilePath);
    if(!dir_sql.exists())
        dir_sql.mkpath(sqlfilePath);

    //write to local sql database.
    ExcelThread *threadexlsR = new ExcelThread(sqlfileName,ExcelThread::ExcelOperatorType::WriteData,this);
    rec.setFileName(sqlfileName);
    threadexlsR->setExlHandle(rec);
    threadexlsR->start();
    connect(threadexlsR,&ExcelThread::finishedWriteToSql,this,&FormRecordControl::updateEnable,Qt::QueuedConnection);
}

void FormRecordControl::Init()
{
    ui->btn_add->setVisible(false);
    ui->btn_return->setVisible(false);

    //default toolBox
    for(int i = 0;i<ui->toolBox->count();i++)
        ui->toolBox->removeItem(i);

    ui->scrollArea->setMinimumHeight(200);
    ui->toolBox->setMinimumHeight(200);
    setMaximumHeight(300);
    ui->btn_showEnable->setVisible(true);

    connect(this,SIGNAL(sig_showMsg(QString)),this,SLOT(showMessage(QString)));
}

/*!
 * 导入处理函数
 * \brief FormRecordControl::Init_Add
 */
void FormRecordControl::Init_Add()
{
    ui->horizontalLayout_Widget->setContentsMargins(ui->horizontalLayout_Widget->contentsMargins() + QMargins(5,0,0,0));

    for(int i = 0;i<ui->toolBox->count();i++)
        ui->toolBox->removeItem(i);

    ui->scrollArea->setFixedWidth(147);
    ui->toolBox->setFixedWidth(147);

    QSettings setting;
    setting.beginGroup("GroupData");
    QStringList listGroup = setting.childGroups();
    QMap<int,QString> mapGroup;
    foreach(QString str,listGroup){
        mapGroup.insert(str.toInt(),str);
    }
    QMapIterator<int,QString> itorGroup(mapGroup);
    int num_toolbox = 0;
    while(itorGroup.hasNext()){
        itorGroup.next();
        QString groupNum(itorGroup.value());
        //GroupIemData增加对应每一餐TableWidget
        //以getTableWidget、setTableWidget方式进行插入及获取对应当前餐数表数据
        FormToolBoxWidget *itemWidget = new FormToolBoxWidget(ui->toolBox);
        //reload button connect-->first load;
        connect(itemWidget,&FormToolBoxWidget::sig_reloadButton,[=]{
            QRegExp reg("(\\d{1,})");
            if(reg.indexIn(ui->toolBox->itemText(ui->toolBox->currentIndex())) != -1)
            {
                if(!ImportData(reg.cap(1).toInt(),num_toolbox).isEmpty()){
                    if(QMessageBox::Yes == QMessageBox::question(this,"",
                                                                QStringLiteral("无法在数据文件夹中找到对应数据文件（Excel），是否手动指定导入文件，点击是打开?")
                                                                ))
                    {
                        QSettings setting;
                        QString dirPath = setting.value("general/DefaultSaveDir",QStandardPaths::DataLocation).toString();
                        ImportData(reg.cap(1).toInt(),num_toolbox,QFileDialog::getOpenFileName(this, QStringLiteral("打开数据文件"),
                                                                                               dirPath,
                                                                                               tr("*")));
                    }
                }
            }
            qDebug()<<("sig_reloadButton")<<reg.cap(0)<<reg.cap(1)<<num_toolbox;
        });
        ui->toolBox->insertItem(num_toolbox,itemWidget,(QStringLiteral("组号：") + groupNum));
        if(itorGroup.value() == "1")
        {
            int i(num_toolbox);
            auto *it_widget = qobject_cast<FormToolBoxWidget*>(ui->toolBox->widget(i));
            it_widget->setTitle("","");

            if(it_widget){
                foreach(QString str,getTablesName())
                    it_widget->addItem(str);

                connect(it_widget,&FormToolBoxWidget::sig_currentItemChanged,[=](QListWidgetItem * current, QListWidgetItem * /*previous*/){
                    if(!current)return;
                    getCurrentItemData(current);
                });
                it_widget->setCurrentItem();

            }
        }
        num_toolbox++;
    }
    setting.endGroup();

    connect(ui->toolBox,&QToolBox::currentChanged,[=]{
        if(!qobject_cast<FormToolBoxWidget*>(ui->toolBox->currentWidget())->getFillDataFlag())
        {
            auto *it_widget = qobject_cast<FormToolBoxWidget*>(ui->toolBox->currentWidget());
            it_widget->setTitle("","");

            foreach(QString str,getTablesName())
                it_widget->addItem(str);

//            if(!it_widget->getListWidget()->count())
//                ui->tableWidget->clear();
            connect(it_widget,&FormToolBoxWidget::sig_currentItemChanged,[=](QListWidgetItem * current, QListWidgetItem * /*previous*/){
                if(!current)return;
                getCurrentItemData(current);
            });

            it_widget->setCurrentItem();
        }
    });

    connect(ui->btn_add,&QToolButton::clicked,[=]{
//        LoadingWidget *widget_load;
        QDir dir(m_defaultDataPath);
        dir.setFilter(QDir::Files|QDir::NoDotAndDotDot);
       if(!dir.entryList().count()){
           QMessageBox::about(this,QStringLiteral(""),QStringLiteral("数据文件夹未发现数据文件，请先准备数据文件,当前数据文件夹路径为：") + (m_defaultDataPath));
           return;
       }
        if(!widget_load){
            widget_load = new LoadingWidget(this);
            widget_load->play();
        }
        for(int i = 0;i<ui->toolBox->count();i++){
            QRegExp reg("(\\d{1,})");
            if(reg.indexIn(ui->toolBox->itemText(i)) != -1){
                ImportData(reg.cap(1).toInt(),i);
            }
        }
    });

    ui->toolBox->setCurrentIndex(0);
    //    qDebug()<<"checkData:"<<getItemFileName()<<getTablesName();
}

QWidget* FormRecordControl::createSelectTBar(QStringList actionList)
{
    QWidget *widget_selectItem = nullptr;
    if(!widget_selectItem){
        widget_selectItem = new QWidget(this);
        widget_selectItem->setStyleSheet("background-color:rgb(222,238,255);");
        widget_selectItem->setWindowFlags(widget_selectItem->windowFlags() | Qt::Popup);
        widget_selectItem->setAttribute(Qt::WA_DeleteOnClose);

        widget_selectItem->setLayout(new QVBoxLayout);
        QVBoxLayout *vlayout = qobject_cast<QVBoxLayout*>(widget_selectItem->layout());
        foreach(QString str,actionList){
            int index = ui->toolBox->currentIndex();
            for(int i=0;i<ui->toolBox->count();i++){
                if(ui->toolBox->itemText(i).contains(str)){
                    index = i;
                    break;
                }
            }
            QCheckBox *chk = new QCheckBox(str,this);
            connect(chk,&QCheckBox::stateChanged,[=](int state){
                ui->toolBox->setItemEnabled(index,state);
            });
            chk->setCheckable(true);
            chk->setChecked(ui->toolBox->isItemEnabled(index));
            vlayout->addWidget(chk);
        }
    }
    return widget_selectItem;
}

QSqlDatabase FormRecordControl::dbcon(QString m_filename)
{
    QFileInfo fileInfo(m_filename);
    QUuid uid = QUuid::createUuid();
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","w_" + fileInfo.baseName()+ uid.toString());
    db.setDatabaseName(m_filename );

    if(QFile::exists(m_filename))
    {
        if(!db.open()){
            qDebug()<<__LINE__<<("openDb error:%s",db.lastError())<<fileInfo.baseName();
        }
//        return db;
    }
    return db;
}

QString FormRecordControl::getItemDBFileName(int index)
{
    if(index == -1){
        if(ui->toolBox->count()){
            QRegExp regnum("[\\d]{1,}");
            QString tblGroupNum = "";
            QString findtext = ui->toolBox->itemText(ui->toolBox->currentIndex());
            if(regnum.indexIn(findtext) != -1)
                tblGroupNum = regnum.cap(0);
            index = tblGroupNum.toInt();
        }
        else
            return"";
    }

    QString sqlfilePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QDir::separator() + "config";
    QString m_filename = sqlfilePath + QDir::separator() + QString("dbrec_%1.db").arg(index);
    return m_filename;
}

QString FormRecordControl::getItemExlFileName(int index)
{
    //file search.
    QSettings setting;
    QString dirPath = setting.value("general/DefaultSaveDir",QStandardPaths::DataLocation).toString();
    QDir dir(dirPath);
    if(!dir.exists()){
        QMessageBox::about(0,QStringLiteral(""),QStringLiteral("Directory cant find."));
        return QStringLiteral("Directory cant find.");
    }

    dir.setFilter(QDir::Files|QDir::NoDotAndDotDot);
    dir.setSorting(QDir::Name | QDir::IgnoreCase);
    QString matchFileName("");
    foreach(QString str,dir.entryList()){
        QRegExp reg("(\\d{1,})-.*");
        if(reg.indexIn(str) != -1){
            if(reg.cap(1).toInt() == index){
                //start import data from excel with thread.
                matchFileName = str;
                break;
            }
        }
    }
    if(matchFileName.isEmpty())
        return "";
    return dir.absoluteFilePath(matchFileName);
}

void FormRecordControl::initTableWidget(QString tblName)
{
    QTableWidget *tablwnd = new QTableWidget(this);//m_ItemData.setTableWidget();
    //init tablewidget
    QString tblwndStyle = "QTableWidget{\n	background:white;\n	border:1px solid rgb(137,137,199);\n	border-top:0px;\n	border-right:0px;\n	border-bottom:0px;\n}";
    tablwnd->setStyleSheet(tblwndStyle);
    tablwnd->setColumnCount(24);
    tablwnd->setRowCount(3);
    tablwnd->setVerticalHeaderLabels(QStringList()<<QStringLiteral("箱号")<<QStringLiteral("投喂值")<<QStringLiteral("称量值"));
    m_ItemData.setTableWidget(tblName/*tblName*/,tablwnd);
    ui->stackedWidget->addWidget(tablwnd);
    ui->stackedWidget->widget(ui->stackedWidget->count()-1)->setProperty("tableName",tblName);

    //内容修改自动调整单元格大小
    connect(tablwnd,&QTableWidget::cellChanged,[=](int /*row*/, int column){
        tablwnd->resizeColumnToContents(column);
    });

//    connect();
}

/*!
 * 导入处理函数
 * \brief FormRecordControl::getCurrentItemData
 * \param stritem
 * \param isToFeed [true:用作投料界面;false:用作导入界面]
 */
void FormRecordControl::getCurrentItemData(QString stritem,bool isToFeed)
{
    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(24);
    ui->tableWidget->setRowCount(3);
    ui->tableWidget->setVerticalHeaderLabels(QStringList()<<QStringLiteral("箱号")<<QStringLiteral("投喂值")<<QStringLiteral("称量值"));

//    QTableWidget *tablwnd = NULL;
//    tablwnd = m_ItemData.getTableWidget(stritem);
//    QTableWidget *tablwnd = ui->tableWidget;
    int m_count = 0;

    //"D:/My Documents/My Local/YanboOrg/FishSoftware\config\dbrec_2.db"
    QString dbFileName = getItemDBFileName();
    if(isToFeed){//GroupData()
        qDebug()<<"getCurrentItemData___:"<<m_ItemData.getGroupNum()<<dbFileName;
        QRegExp regexp("[\\d]{1,}");
        dbFileName.replace(regexp,GroupData().getGroupNum());
//        dbFileName = "";//组号
    }
    QSqlDatabase db = dbcon(dbFileName);
    if(!db.isValid())
        return;
//    QSqlQuery query(db);
    QSqlQuery query = QSqlQuery::QSqlQuery(db);

    if(query.exec(QString("select * from %1").arg(stritem)))
    {
        qDebug()<<"check:"<<db.isValid()<<db.isOpen()<<db.isOpenError();
        QHash<QString,QString> hash_realvalue;
        if(m_eachRealValue.constFind(stritem)!=m_eachRealValue.constEnd()){
            hash_realvalue = m_eachRealValue.constFind(stritem).value();
        }
        while (query.next()){
            //init data.
			QString boxnum = query.value("boxnum").toString();
			QString boxvalue = query.value("boxvalue").toString();
            QString boxreal="";
            if(hash_realvalue.isEmpty())
                hash_realvalue.insert(boxnum,"");
            else{
                QHash<QString,QString>::const_iterator itorhash = hash_realvalue.constFind(boxnum);
                if(itorhash != hash_realvalue.constEnd())
                    boxreal = itorhash.value();
            }

            auto *itemBox = new QTableWidgetItem(boxnum);
            auto *itemValue = new QTableWidgetItem(boxvalue);
            auto *itemRValue = new QTableWidgetItem(boxreal);
            itemBox->setTextAlignment(Qt::AlignCenter);
            itemValue->setTextAlignment(Qt::AlignCenter);
            itemRValue->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(0,m_count,itemBox);
            ui->tableWidget->setItem(1,m_count,itemValue);
            ui->tableWidget->setItem(2,m_count,itemRValue);
            ui->tableWidget->resizeColumnToContents(m_count++);
        }
        m_eachRealValue.insert(stritem,hash_realvalue);
    }
    qDebug()<<"check:"<<query.lastError()<<query.lastQuery();

//    ui->tableWidget->setVerticalHeaderLabels(QStringList()<<QStringLiteral("箱号")<<QStringLiteral("投喂值")<<QStringLiteral("称量值"));
}

void FormRecordControl::getCurrentItemData(QListWidgetItem *item)
{
    foreach(QString str,getTablesName()/*get current Item text.*/)
    {
        if(item->text().contains(str)){
            getCurrentItemData(str);
            break;
        }
    }
}

QStringList FormRecordControl::getTablesName(QString itemtext)
{
    QRegExp regnum("[\\d]{1,}");
    QString tblGroupNum = "";
    QString findtext = itemtext.isEmpty()?ui->toolBox->itemText(ui->toolBox->currentIndex()):itemtext;
    if(regnum.indexIn(findtext) != -1)
        tblGroupNum = regnum.cap(0);
    QString m_filename = getItemDBFileName(regnum.cap(0).toInt());
    qDebug()<<"getItemFileName(regnum.cap(0).toInt()):"<<QFile::exists(m_filename)<<m_filename<<getItemDBFileName(regnum.cap(0).toInt())
           <<regnum.cap(0)<<itemtext;
    if(!QFile::exists(m_filename))
        return QStringList();
    QSqlDatabase db = dbcon(m_filename);
    QSqlQuery query(db);
    query.exec("select name from sqlite_master where type='table' order by name;");
    QStringList tbls;
    QRegExp regtbl(".*[\\d]{1,}.*");
    while(query.next()){
        if(regtbl.indexIn(query.value("name").toString()) != -1){
            tbls.append(query.value("name").toString());
        }
    }
    return tbls;
}

void FormRecordControl::showMessage(const QString msg)
{
    if(widgetmsg == NULL){
        widgetmsg = new QWidget(0);
        widgetmsg->setWindowTitle(QStringLiteral("出错列表"));
        widgetmsg->setAttribute(Qt::WA_DeleteOnClose);
        QListWidget *liswidget = new QListWidget(widgetmsg);
        liswidget->setObjectName("listWidgetOfShowMsg");
        QVBoxLayout *vbox = new QVBoxLayout;
        vbox->addWidget(liswidget);
        widgetmsg->setLayout(vbox);
    }
    QListWidget *listwnd = widgetmsg->findChild<QListWidget*>("listWidgetOfShowMsg");
    if(listwnd){
//        QListWidgetItem *item = new QListWidgetItem;
        listwnd->addItem(msg);
//        QLineEdit *lineEdit = new QLineEdit(listwnd);
//        lineEdit->setStyleSheet("QLineEdit{background:transparent;border:transparent;border-bottom:1px solid lightgray;color:gray;}"
//                                "QLineEdit:hover{border-bottom:2px solid rgb(51,153,255);color:rgb(51,153,255);}");
//        listwnd->setItemWidget(item,lineEdit);
    }
    widgetmsg->showNormal();
    widgetmsg->activateWindow();

//    QMessageBox::about(0,QStringLiteral("提示"),msg);
}
